package cn.tl.base.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("U-TOKEN");
        if (token!=null){
            //获取redis是否有值
            Object o = redisTemplate.opsForValue().get(token);
            if(o!=null){
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                return true;
            }
        }
        response.setContentType("application/javascript; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        //{"success":false,"message":"noAuth"}
        writer.println("{\"success\":false,\"message\":\"noAuth\"}");

        return false;
    }
}
